package com.sgb.kjwl.view.ui.activity.manage

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.scwang.smart.refresh.layout.listener.ScrollBoundaryDecider
import com.sgb.kjwl.AppActivity
import com.sgb.kjwl.BR
import com.sgb.kjwl.R
import com.sgb.kjwl.databinding.ActivityWebsiteAddressBinding
import com.sgb.kjwl.databinding.ItemWebsiteAddressBinding
import com.sgb.kjwl.di.manage.DaggerEnterpriseManageComponent
import com.sgb.kjwl.di.manage.EnterpriseManageModule
import com.sgb.link.entity.WebSiteAddressEntity
import com.sgb.kjwl.viewmodel.manage.WebsiteAddressModel
import com.swgk.core.base.aroute.AppRouteConstant
import com.swgk.core.base.di.AppComponent
import com.swgk.core.recyclerview.decoration.RecyclerCustomDecoration
import com.swgk.core.util.MToast
import javax.inject.Inject

/**
 * 地址管理
 */
@Route(path = AppRouteConstant.WEBSITE_ADDRESS)
class WebSiteAddressActivity : AppActivity() {

    @Inject
    lateinit var mViewModel: WebsiteAddressModel

    private lateinit var mBinding: ActivityWebsiteAddressBinding
    private var isLoadMore = false //是否加载更多
    private lateinit var mAdapter: AddressAdapter
    private var isEnableLoadMore = false //是否可以上拉加载

    private var mSiteType: Int? = null //网站类型, 1 企业 2 团队0 个人

    @Autowired(name = "types")
    @JvmField
    var types: Int = 0

    @Autowired(name = "isARouter")
    @JvmField
    var isARouter = false

    companion object {
        const val KEY_SITE_TYPE = "key_site_type"
        const val REFRESH_REQUEST_CODE = 10010
        private var mRequestCode: Int? = null

        fun launch(context: Context, siteType: Int) {
            val intent = Intent(context, WebSiteAddressActivity::class.java)
            intent.putExtra(KEY_SITE_TYPE, siteType)
            context.startActivity(intent)
        }

        /**
         * 供各模块调用
         */
        fun launch(activity: Activity, siteType: Int, requestCode: Int) {
            val intent = Intent(activity, WebSiteAddressActivity::class.java)
            intent.putExtra(KEY_SITE_TYPE, siteType)
            mRequestCode = requestCode
            activity.startActivityForResult(intent, requestCode)
        }
    }


    override fun setupActivityComponent(appComponent: AppComponent?) {
        DaggerEnterpriseManageComponent.builder().appComponent(appComponent)
                .enterpriseManageModule(EnterpriseManageModule()).build().inject(this)
    }

    override fun initView() {
        if (isARouter) {
           mSiteType = types
            mRequestCode = 10021;//集采供方报价时选择地址使用
        } else {
            if (intent != null) {
                mSiteType = intent!!.getIntExtra(KEY_SITE_TYPE, 1)
            }
        }
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_website_address)
        mBinding.include.titleView.text = "地址管理"
        mBinding.include.ivBack.setOnClickListener { finish() }
        mBinding.include.rightView.text = "新增地址"
        mBinding.include.rightView.setOnClickListener { view1 ->
            WebSiteAddAddressActivity.launchForResult(this, mSiteType!!, REFRESH_REQUEST_CODE)
        }
        initRecycleView()
        mViewModel.mAddressList.observe(this, {
            if (it == null) {
                return@observe
            }
            isEnableLoadMore = it.size >= 10
            if (isLoadMore) {
                mAdapter.addData(it)
            } else {
                mAdapter.setNewData(it)
            }
        })
        mViewModel.message.observe(this, {
            if (!TextUtils.isEmpty(it)) {
                MToast.showToast(this, it)
                isLoadMore = false
                mViewModel.getNewUserAddress(this, mSiteType!!, isLoadMore)
            }
        })
    }

    override fun init() {
        super.init()
        isLoadMore = false
        mViewModel.getNewUserAddress(this, mSiteType!!, isLoadMore)
    }


    private fun initRecycleView() {
        mBinding.recycleView.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
        // SwipeRefreshLayout 刷新
        mBinding.refreshLayout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onLoadMore(refreshLayout: RefreshLayout) {
                isLoadMore = true
                mViewModel.getNewUserAddress(this@WebSiteAddressActivity, mSiteType!!, isLoadMore)
                mBinding.refreshLayout.finishLoadMore(500)
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                isLoadMore = false
                mViewModel.getNewUserAddress(this@WebSiteAddressActivity, mSiteType!!, isLoadMore)
                mBinding.refreshLayout.finishRefresh(500)
            }
        })
        //解决 在实现 上拉加载更多 和 下拉刷新 时  遇到item不在顶端就执行了刷新的方法和数据item没有填满屏幕也执行了加载更多
        mBinding.refreshLayout.setScrollBoundaryDecider(object : ScrollBoundaryDecider {
            override fun canRefresh(content: View): Boolean {
                if (mBinding.recycleView == null) return false
                return mBinding.recycleView.computeVerticalScrollOffset() === 0
            }

            override fun canLoadMore(content: View): Boolean {
                if (mBinding.recycleView == null) return false
                //整个View控件的高度
                val scrollRange: Int = mBinding.recycleView.computeVerticalScrollRange()
                //当前屏幕之前滑过的距离
                val scrollOffset: Int = mBinding.recycleView.computeVerticalScrollOffset()
                //当前屏幕显示的区域高度
                val scrollExtent: Int = mBinding.recycleView.computeVerticalScrollExtent()
                //获取recyclerView的高度
                val height: Int = mBinding.recycleView.height
                if (height > scrollRange) {
                    return false
                }
                return isEnableLoadMore && scrollRange <= scrollOffset + scrollExtent
            }
        })
        //mBinding.refreshLayout.setScrollBoundaryDecider(SimpleBoundaryDecider())
        mAdapter = AddressAdapter(R.layout.item_website_address)
        mAdapter.bindToRecyclerView(mBinding.recycleView)
        val empty = LayoutInflater.from(this).inflate(R.layout.layout_empty_view, mBinding.recycleView, false)
        mAdapter.emptyView = empty
        mBinding.recycleView.addItemDecoration(
                RecyclerCustomDecoration(
                        0f,
                        0f,
                        0f,
                        resources.getDimension(R.dimen.dp1), resources.getColor(R.color.color_main_bg)
                )
        )
        mAdapter.setCallBack(object : ClickCallBack {
            override fun deleteById(entity: WebSiteAddressEntity?, position: Int) {
                if (entity?.siteType == null) {
                    return
                }
                //if (entity.siteType == 0){
                mViewModel.bathDel(this@WebSiteAddressActivity, "" + entity.id)
//            } else if (entity.siteType == 1){
//               mViewModel.companyAddressDel(this@WebSiteAddressActivity, "" + entity.id)
//            }
            }

            override fun editById(entity: WebSiteAddressEntity?, position: Int) {
                if (entity == null) {
                    return
                }
                WebSiteAddAddressActivity.launchForResult(this@WebSiteAddressActivity, entity, mSiteType!!, REFRESH_REQUEST_CODE)
            }

            override fun setDefault(entity: WebSiteAddressEntity?, position: Int) {
                if (entity == null) {
                    return
                }
                if (entity.isDefaultAddress()) {
                    return
                }
                entity.status = "1"//1代表默认
                mViewModel.saveOrUpdateAddress(this@WebSiteAddressActivity, entity, false)
            }

            override fun onItem(entity: WebSiteAddressEntity?, position: Int) {
                if (mRequestCode == null) return
                val intent = Intent()
                intent.putExtra("data", mAdapter.getItem(position))
                setResult(RESULT_OK, intent)
                finish()
            }
        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK && requestCode == REFRESH_REQUEST_CODE) {
            isLoadMore = false
            mViewModel.getNewUserAddress(this, mSiteType!!, isLoadMore)
        }
    }


    class AddressAdapter(layoutResId: Int) : BaseQuickAdapter<WebSiteAddressEntity, BaseViewHolder>(layoutResId) {
        private var mItemBinging: ItemWebsiteAddressBinding? = null
        private var mCallBack: ClickCallBack? = null
        fun setCallBack(mCallBack: ClickCallBack) {
            this.mCallBack = mCallBack
        }

        override fun convert(helper: BaseViewHolder?, item: WebSiteAddressEntity?) {
            mItemBinging = DataBindingUtil.bind(helper!!.itemView)
            mItemBinging!!.setVariable(BR.viewModel, item)
            mItemBinging!!.executePendingBindings()
            mItemBinging!!.radioIsDef.setOnClickListener {
                if (item == null || item.isDefaultAddress()) {
                    return@setOnClickListener
                }
                if (mCallBack != null) {
                    mCallBack!!.setDefault(item, helper.layoutPosition)
                }
            }
            mItemBinging!!.tvAddressDefault.setOnClickListener {
                if (item == null || item.isDefaultAddress()) {
                    return@setOnClickListener
                }
                if (mCallBack != null) {
                    mCallBack!!.setDefault(item, helper.layoutPosition)
                }
            }

            mItemBinging!!.ivEdit.setOnClickListener {
                if (mCallBack != null) {
                    mCallBack!!.editById(item, helper.layoutPosition)
                }
            }

            mItemBinging!!.tvDel.setOnClickListener {
                if (mCallBack != null) {
                    mCallBack!!.deleteById(item, helper.layoutPosition)
                }
            }
            mItemBinging!!.llItem.setOnClickListener {
                if (mCallBack != null) {
                    mCallBack!!.onItem(item, helper.layoutPosition)
                }
            }
        }
    }

    interface ClickCallBack {
        fun deleteById(entity: WebSiteAddressEntity?, position: Int)
        fun editById(entity: WebSiteAddressEntity?, position: Int)
        fun setDefault(entity: WebSiteAddressEntity?, position: Int)
        fun onItem(entity: WebSiteAddressEntity?, position: Int)
    }
}